<?php
include("../config.php");
include('phpQuery.php');
$GLOBALS['debugger']['ponit'] = array();//列表6 正文1 抓取和编码2 专业抓取includetemp等3
//断点处添加条件 in_array(6,$GLOBALS['debugger']['ponit'])||in_array(1,$GLOBALS['debugger']['ponit'])
ini_set('max_execution_time', '600');
ini_set('memory_limit', '5120M');
set_time_limit(600);
$argv[1]=$argv[1]??"";
if($argv[1]==1){
    $_GET['s_url']="https://item.taobao.com/item.htm?id=733102869847&pisk=g2StpY0BiWVMz0ME0jaHoHznjWy3riBZs1WSmIAil6CdFTlMlI4NMECcTEsMjOfKQMC-mcVa7tivmnNuZuqlQ9K2c7bot-9nQKv-lqGDlX9B0bZJ7DZlQORqBjwlRu0Y1gYq5qOfGHTBHKxXCK96OJpveItX1EGIRLOBGn1X5DGBIKm6CF9XAJpW3c96cEMIRdvscf1XcJLINHVvOAOmDZ-QNqkaKpnjcMp9RyX6O2dcAdKewOst20H2BFd5CBFl_5GDRt8A0xovkO_PgL1s17YNhwCpBnEn536dl_pFfuc9LNXCEB6-3mWwXKLWceHjc9KwOUsBVuGpLw6GlG5tHm9NjgYvaeej0ExCqU_56xyPdh9fgUS0acR1hTSPr3En536dl_QA4zSl2eMmZQpm5JeKuq86LUxM0cw8FZU9pQ2TDqu28JJpZJeKuq86LpduB-3queyF.&priceTId=214782b117276777049216734e51f3&spm=a21bo.jianhua%2Fa.201876.d6.5af92a89zDjou3&utparam=%7B%22aplus_abtest%22%3A%220a7ae7a39e3fd3cb0de258f904e26a3c%22%7D&xxc=ad_ct";
    $_GET['bug']=1;
    $_GET['htmlpageuse']=2; //2页面从缓存读取
}

header('Content-Type:text/html;charset=utf-8');
$theValue=$theValue??"";
$theValue = stripslashes($theValue);
$nn55 = array();
$GLOBALS['returncookie'] = "";
$GLOBALS['jumpurl'] = "";
$addreturn = array();
$pageinfo = array();
$cookie = "";
$longthis=null;
$options=array();
$cid=0;
$driver=null;
$urlparams=array();
require_once(APP_PATH . "/collect/config.php");
require_once(APP_PATH . "/collect/Lib/CollcetLib/CollectTongyong.class.php");
include_once(APP_PATH . "/collect/Lib/CollcetLib/getPageContentClass.class.php");
require_once(APP_PATH . "/collect/Lib/ORG/auto_phpcms.class.php");
require_once(APP_PATH . "/collect/Lib/ORG/auto_discuz.class.php");
require_once(APP_PATH . "/collect/Lib/ORG/Mycurl.class.php");
include_once(APP_PATH.  "/collect/selenium_header.php");
require_once(APP_PATH . "/collect/source/plugin/mobile/json.class.php");
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverExpectedCondition;
use Facebook\WebDriver\WebDriverWait;
use collect\classes;

$capabilities = DesiredCapabilities::chrome();
$capabilities->setCapability(ChromeOptions::CAPABILITY, $options);

function loadclass($classname){
    if(file_exists($classname.'.php')){
        include_once $classname.'.php';
    }elseif(file_exists(APP_PATH."/collect/Lib/ORG/".$classname.'.php')){
        include_once APP_PATH."/collect/Lib/ORG/".$classname.'.php';
    }elseif(file_exists(APP_PATH."/collect/Lib/ORG/".$classname.'.class.php')){
        include_once APP_PATH."/collect/Lib/ORG/".$classname.'.class.php';
    }
}

spl_autoload_register( 'loadclass' );
if($_REQUEST['temp']==1){
    execute("truncate table my");
}
$GLOBALS['mycurl']=$c=new Mycurl();
$yong = new CollectTongyong();
$GLOBALS['zhongsj'] = 60; //抓取列表的最长总时间
$GLOBALS['onepage'] = 20; //分页文章处理的最长抓取时间
$GLOBALS['mycurl'] = new Mycurl();
$t = new t();
$zqstr="";
//unlinkTemp();
//$_GET['s_url']="http://www.gx.xinhuanet.com/newscenter/yw.htm";
//$_GET['gather_type']=6;
//$_GET['nozqnr']=1;
//$_GET['bug']=1;
//$_GET['api']=1;
//print_r(json_encode($_POST));exit;

$s_url = $_REQUEST['s_url'] = (!preg_match("/https?\:\/\//Uisx", $_REQUEST['s_url'])) ? urldecode($_REQUEST['s_url']) : $_REQUEST['s_url'];
//$s_url =urldecodeUrl($s_url);
$_POST['notclfdl']=$_POST['notclfdl']??"";
$_GET['notclfdl']=$_GET['notclfdl']??"";
if ($_POST['notclfdl']) {
    $notclfdl = $_POST['notclfdl'];
} elseif ($_GET['notclfdl']) {
    $notclfdl = $_GET['notclfdl'];
}
//$_REQUEST['notclfdl']=1;//不处理防盗链

$_POST['jumpcacheids']=$_POST['jumpcacheids']??"";
if($_POST['jumpcacheids']){
    $jumpcacheids=unserialize($_POST['jumpcacheids']);
}

if ($_POST['gather_type']) {
    $gather_type = $_POST['gather_type'];
} elseif ($_GET['gather_type']) {
    $gather_type = $_GET['gather_type'];
}


$_POST['jsonp']=$_POST['jsonp']??"";
$_GET['jsonp']=$_GET['jsonp']??"";
if ($_POST['jsonp']) {
    $jsonp = $_POST['jsonp'];
} elseif ($_GET['jsonp']) {
    $jsonp = $_GET['jsonp'];
}

$_POST['gindex']=$_POST['gindex']??"";
$_GET['gindex']=$_GET['gindex']??"";
if ($_POST['gindex'] != "") {
    $gindex = $_POST['gindex'];
} elseif ($_GET['gindex'] != "") {
    $gindex = $_GET['gindex'];
}
$_POST['code']=$_POST['code']??"";
$_GET['code']=$_GET['code']??"";
if ($_POST['code']) {
    $code = $_POST['code'];
} elseif ($_GET['code']) {
    $code = $_GET['code'];
}
if ($_POST['source']) {
    $source = $_POST['source'];
} elseif ($_GET['source']) {
    $source = $_GET['source'];
}

$_POST['viewlists']=$_POST['viewlists']??"";
$_GET['viewlists']=$_GET['viewlists']??"";
if ($_POST['viewlists']) {
    $viewlists = $_POST['viewlists'];
} elseif ($_GET['viewlists']) {
    $viewlists = $_GET['viewlists'];
}
$viewlists = preg_match("/viewlists=1/", $s_url) ? 1 : 0;

$_POST['nozqnr']=$_POST['nozqnr']??"";
$_GET['nozqnr']=$_GET['nozqnr']??"";
if ($_POST['nozqnr']) {
    $nozqnr = $_POST['nozqnr'];
} elseif ($_GET['nozqnr']) {
    $nozqnr = $_GET['nozqnr'];
}

if ($_POST['ptid']) {
    $ptid = $_POST['ptid'];
} elseif ($_GET['ptid']) {
    $ptid = $_GET['ptid'];
}
$_POST['tid']=$_POST['tid']??"";
$_GET['tid']= $_GET['tid']??"";
if ($_POST['tid']) {
    $tid = $_POST['tid'];
} elseif ($_GET['tid']) {
    $tid = $_GET['tid'];
}

if ($_POST['host']) {
    $host = $_POST['host'];
} elseif ($_GET['host']) {
    $host = $_GET['host'];
}

if ($_POST['loginurl']) {
    $loginurl = $_POST['loginurl'];
} elseif ($_GET['loginurl']) {
    $loginurl = $_GET['loginurl'];
}

if ($_POST['loginyzm']) {
    $loginyzm = $_POST['loginyzm'];
} elseif ($_GET['loginyzm']) {
    $loginyzm = $_GET['loginyzm'];
}
$_POST['onlybt']=$_POST['onlybt']??"";
$_GET['onlybt']=$_GET['onlybt']??"";
if ($_POST['onlybt']) {
    $onlybt = $_POST['onlybt'];
} elseif ($_GET['onlybt']) {
    $onlybt = $_GET['onlybt'];
}


if (isset($_POST['api'])) {
    $api = $_POST['api'];
} elseif (isset($_GET['api'])) {
    $api = $_GET['api'];
} else {
    $api = 0;
}

if (preg_match("/%26api%3D1|api=1/", $thisurl)) {
    $wapi = 1;
}
$_POST['username']=$_POST['username']??"";
$_GET['username']=$_GET['username']??"";
if ($_POST['username']) {
    $username = $_POST['username'];
} elseif ($_GET['username']) {
    $username = $_GET['username'];
}
$_POST['password']=$_POST['password']??"";
$_GET['password']=$_GET['password']??"";
if ($_POST['password']) {
    $password = $_POST['password'];
} elseif ($_GET['password']) {
    $password = $_GET['password'];
}

if (isset($_POST['bug'])) {
    $bug = $_POST['bug'];
} else if (isset($_GET['bug'])) {
    $bug = $_GET['bug'];
} else {
    $bug = 0;
}

if ($bug == 0) {
    if (preg_match("/bug=1/", $s_url)) {
        $bug = 1;
    }
}

//要从www.google.com抓取相似图片 g=1
if (isset($_POST['g'])) {
    $g = $_POST['g'];
} else if (isset($_GET['g'])) {
    $g = $_GET['g'];
} else {
    $g = 0;
}

//$_REQUEST['max']=1;  //有这参数，列表页如果不指定zq,则自动选取最多的数据的zq

if ($_POST['cookie']) {
    $cookie = $_POST['cookie'];
} elseif ($_GET['cookie']) {
    $cookie = $_GET['cookie'];
}


if($_REQUEST['action']=="deletecache"){
    execute("DELETE FROM longzs.`cache` WHERE id={$_REQUEST['cacheid']}");
    $data=array();
    $data['cacheid']=$_REQUEST['cacheid'];
    $msg="缓存已经删除！";
    json_exit($data,$msg,1);
}

if($_REQUEST['action']=="savecookie"){
    $data=array();
    $data['cookie']=trim($_REQUEST['cookie']);
    $id=insertupdate("longzs.longzs_re",$data,"select id from longzs.longzs_re where host='{$_REQUEST['host']}'");
    execute("update longzs.longzs_re set cookie='{$_REQUEST['cookie']}' where host='{$_REQUEST['host']}'");
    $data=array();
    $data['cookie']=$_REQUEST['cookie'];
    $msg="cookie已经保存！";
    json_exit($data,$msg,1);
}

if($_REQUEST['action']=="saveweb"){
    $raw_post_data = file_get_contents('php://input');
    $data_post = json_decode($raw_post_data, true);
    $url=$data_post["url"];
    $host=host($url);
    $data=array();
    $data['host']=$host;
    $data['cookie']=trim($data_post['cookie']);
    $id=insertupdate("longzs.longzs_re",$data,"select id from longzs.longzs_re where host='{$data['host']}'");
    execute("update longzs.longzs_re set cookie='".safeEasy($data['cookie'])."',update_time='{$data['update_time']}' where host='{$data['host']}'");
    $data=array();
    $data['url']=$url;
    $data['tempnr']=trim($data_post['yuannr']);
    $data['tempnr']=preg_replace('/[^\x{0000}-\x{FFFF}]/u', '',  $data['tempnr']);
    $data['urlcode']= substr(md5($url), 0, 15);
    $cacheid=insertupdate("longzs.cache",$data,"select id from longzs.cache where url='{$url}' or urlcode='{$data['urlcode']}'");
    execute("update longzs.cache set tempnr='".safeEasy($data['tempnr'])."' where url='{$url}' or urlcode='{$data['urlcode']}'");
    $data=array();
    $data['host']=wwwhost($url);
    $data['cookie']=$data_post['cookie'];
    $data['update_time']=date("Y-m-d H:i:s");
    $cacheid=insertupdate("longzs.longzs_cookies",$data,"select id from longzs.longzs_cookies where host='{$host}'");
    execute("update longzs.longzs_cookies set cookie='".safeEasy($data['cookie'])."' where host='{$data['host']}'");
    $data=array();
    $data['cookie']=$data_post['cookie'];
    $data['url']=$url;
    $data['yuannr']=$data_post['yuannr'];
    $data['host']=$host;
    $data['urlid']=$id;
    $data['cacheid']=$cacheid;
    $msg="cacheid:{$cacheid},host:{$host},re_id:{$id},cookie,tempnr已经保存！\nurl:{$url}";
    json_exit($data,$msg,1);
}

if (preg_match("/zq=[0-9]+\b/isx", $s_url)&&$gather_type == 1) {
    $gather_type=6;
}

START:

if ($gather_type == 6) {
    //列表 步骤1 设置lsitid到list库
    $GLOBALS['listid'] = setlisturlid($s_url);
    //列表 2.网址里如果可处理多个网址
    $urls_all = preg_split("/(,|[\r\n]|\;|；)(?=\s*http)/", $s_url);
    $d = array();
    $d_all = array();
    $bbsdata = array();
    $newarr = array();
    $listinfo=array();
    $pageinfo = array();
    $nozqnr=ceil($_REQUEST['nozqnr']);
//    if($_SERVER['PHP_SELF']=="/collect/reset/reset_send.php"&&!$bug){
//        $_REQUEST['nozqnr']=1;
//        $nozqnr=1;
//    }
    //yzs 抓取页多个列表处理
    $listinfo['urls_info']=array("count"=>count($urls_all),"urls"=>$urls_all);
    foreach ($urls_all as $index => $s_url) {
        if (preg_match("/\[(.*)\]/Uisx", $s_url, $nn)) {
            $index = explode(",", $nn[1]);
            for ($j = 0; $j < count($index); $j++) {
                if (preg_match("/([0-9]+)\-([0-9]+)/Uisx", $index[$j], $nn2)) {
                    for ($i = $nn2[1]; $i <= $nn2[2]; $i++) {
                        $newarr[] = str_replace($nn[0], $i, $s_url);
                    }
                } else {
                    $newarr[] = str_replace($nn[0], $index[$j], $s_url);
                }
            }
        } else {
            $newarr[] = $s_url;
        }
    }

    $urls_all = $newarr;
    jsstart("zhongsj");
    foreach ($urls_all as $index => $s_url) {
        $listinfo['urls_info']['index']=$index;
        $s_url=urldecodeUrl($s_url);
        preg_match("/zq=(([0-9,\+]|＋)+)/",$s_url , $nn);
        $gindex = preg_split("/\+|\,(?:http)|＋/", $nn[1]);
        $listid=getlisturlid($s_url);
        header("listid:{$listid}");
        //列表 3.进入获得列表数据
        //列表 步骤2 新开始抓取一个列表
        $mllb = new Zqindex($s_url, '', $gindex, $bug);
        if($mllb->yuannr=="kongHTML"){
            $listinfo['urls_info']['message'].="第".($index+1)."条列表链接({$s_url})抓取不了网页!<br>\r\n";
            $mllb->yuannr="";
            continue;
        }
        //看一下 是否有数据 $mllb->result[0]
        //列表 步骤7 得出列表数据结果
//        if(!empty($mllb->pageinfo)) {
//            $newpageinfo = json_decode($mllb->pageinfo, 1);
//            if (!empty($newpageinfo['lists'][0]['subject'])) {
//                $pageinfo = marpageinfo($pageinfo,$newpageinfo);
//            }
//        }

        //列表 步骤 保存列表数据到cache表，准备供以后抓取
        //$mllb->listPagesUrlsInsertToCacheByListId($mllb->result[0],$listid);
        if ($mllb->yuannr != "") $pageinfo['source'] = $mllb->yuannr;
        if ($mllb->msg && $gindex[0] == "") {
            $pageinfo['code']=1;
            $pageinfo['subject'] = "抓取页存在多个列表，请按提示重新输入要抓取的网址";
            $pageinfo['message'] = $mllb->msg;
            $pageinfo['lists'] = $mllb->result;
            $pageinfo['islist']=2;
            if($pageinfo['bug']==null&&!empty($mllb->_re)){
                $pageinfo['bug']=$mllb->_re;
            }
            $d_all[]=$mllb->result;
        } else {
            $ob = new auto_discuz();
            if ($_REQUEST['onlybt'] || $_REQUEST['nozqnr']) {
                //列表 步骤8A 提取收获的列表数据（如果仅要求标题）
                if($gindex[0]!="") {
                    $page_d = $ob->geturls($mllb->theindex($gindex));
                }elseif($_REQUEST['max']==1){
                    $max=0;
                    for($m=0;$m<count($mllb->result);$m++){
                        if(count($mllb->result[$m])>$max){
                            $max=count($mllb->result[$m]);
                            $maxindex=$m;
                        }
                    }
                    $page_d = $ob->geturls($mllb->theindex(array($maxindex)));
                }else{
                    $page_d = $ob->geturls($mllb->theindex(array($mllb->firstinx)));
                }
                $d_all = array_merge($d_all, $page_d);
                $mllb->listToMessage($d_all);
            } else {
                $ob->seturlsinfo(1, $s_url_y, $gindex, $ptid, $tid, $host);
                //列表 步骤8B 提取收获的列表数据（要求获得全部数据,包括内容）

                if($gindex[0]!="") {
                    $urls = $ob->geturls($mllb->theindex($gindex));
                }elseif($_REQUEST['max']==1){
                    $max=0;
                    for($m=0;$m<count($mllb->result);$m++){
                        if(count($mllb->result[$m])>$max){
                            $max=count($mllb->result[$m]);
                            $maxindex=$m;
                        }
                    }
                    $urls = $ob->geturls($mllb->theindex(array($maxindex)));
                }else{
                    $urls = $ob->geturls($mllb->theindex(array($mllb->firstinx)));
                }

                //==same ==相同 ==数组判断相同
                $pageinfo=$GLOBALS['mycurl']->setListResult($urls,"title","url","dateline", $s_url);
                $pageinfo=json_decode($pageinfo,1);
                if($pageinfo['bug']==null&&!empty($mllb->_re)){
                    $pageinfo['bug']=$mllb->_re;
                }
                //if(!$_REQUEST['bug']&&!$GLOBALS['mycurl']->isNew&&$pageinfo!=null&&count($pageinfo['lists'])>0){
                //    $d=$pageinfo['lists'];
                //}else {
                    //列表 步骤9 列表结果抓取完成，下一步开始抓取里面的内容 ==d==
                    $d = $mllb->zqlistnr($urls, $listid);
                //}

                if (!empty($d)&& !empty($d[0])) {
                    $pageinfo=array();
                    $mllb->listToMessage($d);
                    if($pageinfo['bug']==null&&!empty($mllb->_re)){
                        $pageinfo['bug']=$mllb->_re;
                    }
                    $pageinfo['listsid'] =$listid;
                    $pageinfo['lists'] = $d;
                    if (!$mllb->listnogengxin && !empty($pageinfo) && is_zw($d[0]['message'])) {
                        //列表 步骤11 收集完成所有列表集和内容后 总的$pageinfo 入库
                        $mllb->savePageinfo($mllb->url, $pageinfo, "", "", "", array("gather_type" => 6));
                    }
                }
                if (is_array($d)) {
                    $d_all = array_merge($d_all, $d);
                }
            }
        }
    }

    $viewlists = 1;

    if (is_array($pageinfo)) {
        if($gather_type==1) {
            $pageinfo['status'] = (strlen($pageinfo['message']) < 100) ? 'error' : 'ok';
        }
    }
    if (($api||$nozqnr) && trim($mllb->msg) == "") {
        if (is_string($pageinfo) && $d_all == null) {
            $pageinfo = json_decode($pageinfo, 1)['lists'];
        } else {
            $pageinfo['lists'] = $d_all;
        }
        if($pageinfo['bug']==null&&!empty($mllb->_re)){
            $pageinfo['bug']=$mllb->_re;
        }
        if(!empty($mllb->pagetitle)){
            $pageinfo['pagetitle']=$mllb->pagetitle;
        }
    }
    $pageinfo['cacheid']=$mllb->cacheid;
    $pageinfo['islist']=1;
    //以上的是处理列表页
} else {

    //以下的是处理内容页
    if (!preg_match("/https?\:\/\//Uisx", $s_url)) {
        $s_url = urldecode($s_url);
    }
    $s_url_y = preg_replace("/[\?&]zq=[0-9]+/", "", $s_url);

    //yzs //内容 步骤1
    jsstart("zhongsj");
    $htmlpageuse_first=1;

    $pageinfo = $yong->getPageContent($s_url_y, $gather_type, $bug);

    if($pageinfo=="kongHTML"){
        $pageinfo=array();
        $pageinfo['url']=$s_url;
        $pageinfo['subject']="";
        $pageinfo['message']="";
        $pageinfo['bug']="无法抓取该网页！";
    }elseif ($pageinfo == "islist" || $pageinfo == null || is_array($pageinfo) && $pageinfo['subject'] == "") {
        bug(">\$pageinfo==\"islist\"");
        $gather_type = 6;
        goto START;
    } else {
        if (is_string($pageinfo)) {
            $pageinfo = nodecode($pageinfo);
        }
    }
}

$pageinfo = $yong->clpageinfo_end($pageinfo);
if(substr($_SERVER['REQUEST_URI'],0,25)=="/collect/reset/reset_send"&&$_REQUEST['app']!=1){
    $host=host($s_url);
    $pageinfo['rs']=getrow("select * from longzs_re where host='$host' ORDER BY updatetime DESC");
    if(!empty($addreturn['jsdata'])) {
        $pageinfo['source']=print_r(json_decode($addreturn['jsdata'][0],1),1);
    }
    if(isset($GLOBALS['debugger']['curr'])) {
        for ($i = 0; $i < count($GLOBALS['debugger']['curr']); $i++) {
            $zqstr .= ">>>" . $GLOBALS['debugger']['curr'][$i]['s_url'];
            if (!empty($GLOBALS['debugger']['curr'][$i]['zqff'])) {
                for ($j = 0; $j < count($GLOBALS['debugger']['curr'][$i]['zqff']); $j++) {
                    $zqstr .= PHP_EOL . "【{$GLOBALS['debugger']['curr'][$i]['zqff'][$j]}】";
                }
            }
            $zqstr .= PHP_EOL;
        }
    }
    if(!empty($GLOBALS['bugmessage'])){
        for($u=0;$u<count($GLOBALS['bugmessage']);$u++){
            $zqstr.=$GLOBALS['bugmessage'][$u];
        }
    }

    if(!is_string($pageinfo['bug'])){
        $pageinfo['bug']=print_r($pageinfo['bug'],1);
    }
    
    if(!empty($GLOBALS['debugger']['jsdata'])){
        $pageinfo['bug'].="在preexe前发现jsdata,详见源文件\r\n";
        $pageinfo['source']=print_r($GLOBALS['debugger']['jsdata'],1);
    }

    $pageinfo['bug']=htmlspecialchars($zqstr.$pageinfo['bug']."\r\n".$GLOBALS['debugger']['pythoncmd']."\r\n");
    $pageinfo= filter($pageinfo);
    $pageinfo['thumb_raw']=urlraw($pageinfo['thumb']);
    $pageinfo['source']=htmlnice($pageinfo['source']);
    unset($pageinfo['source']);
    unset($pageinfo['bug']);
}else{
    unset($pageinfo['bug']);
    unset($pageinfo['source']);
    $pageinfo= filter($pageinfo);
}

if(count($pageinfo['prodata'])>0){
    unset($pageinfo['addreturn']);
    unset($pageinfo['thumb_raw']);
}

//if ($gather_type == 1&& $rs['mustformdbpageinfo']) {
//    $pageinfo = $this->getPageinfoFormDb();
//    $pageinfo['regCode']=1;
//    $pageinfo['islist']=0;
//}
$pageinfo['cid']=$pageinfo['cacheid'];
$pageinfo['elementinfo']=preg_replace("/(http[^\s]+)/","<a href='\\1'>网扯</a>",$GLOBALS['elementInfo']);
$pageinfo['cach']=preg_replace("/(http[^\s]+)/","<a href='\\1'>网扯</a>",$GLOBALS['elementInfo']);
if($_GET["ubb"]==0){
    $pageinfo['message']=ubbtohtml($pageinfo['message']);
}
if(count($pageinfo['thumb'])>1&&(!isset($pageinfo['images'])||empty($pageinfo['images']))){
    $pageinfo['images']=$pageinfo['thumb'];
}



//unset($pageinfo['cacheid']);

if($pageinfo['status']==""){
    $pageinfo['status']="ok";
}

if($_REQUEST['scriptmb']){
    $sc=new Js();
    $sc->setScriptId(1);
    $data=query("select longzs_name as name,{$_REQUEST['shoptype']} as v from longzs.longzs_form_name");
    $name=array();
    for($i=0;$i<count($data);$i++){
        $name[$data[$i]['name']]=$data[$i]['v'];
    }
    $arr=array();
    if($name["subject"]!=""){
        $arr[$name["subject"]]=$pageinfo['subject'];
    }

    if($name["subject1"]!="") {
        $arr[$name["subject1"]] = httpapi("douyin_easy_title",$pageinfo['subject']);
    }

    if($name["jianjie"]!="") {
        $arr[$name["jianjie"]] = "9984";//
    }


    if($name["message"]!="") {
        $arr["message"] = $pageinfo['message'];
    }

    if($name["skus"]!="") {
        //$arr["skus"]=$pageinfo['prodata']['skus'];
    }

    if($name["images"]!="") {
        $arr[$name["images"]] = join(",", $pageinfo['images']);//
    }

    if($name["thumb"]!="") {
        $arr[$name["thumb"]] = $pageinfo['images'][0];
    }

    if($name["flash"]!="") {
        $arr[$name["flash"]] = $pageinfo['flash'];
    }

    if($name["shopname"]!="") {
        $arr["shopname"] = $pageinfo['prodata']['shopName'];
    }

    if($name["attrs"]!="") {
        function customSimilarity($str1, $str2) {
            $charArray1 = preg_split('//u', $str1, -1, PREG_SPLIT_NO_EMPTY);
            $charArray2 = preg_split('//u', $str2, -1, PREG_SPLIT_NO_EMPTY);
            $count = 0;
            foreach ($charArray1 as $char) {
                if (in_array($char, $charArray2)) {
                    $count++;
                }
            }
            $totalChars = max(mb_strlen($str1), mb_strlen($str2));
            $similarity = ($count / $totalChars) * 100;
            return $similarity;
        }

        $shoptype=$_REQUEST['shoptype'];
        foreach ($pageinfo['prodata']['attrs'] as $k=>$v){
            $name=site_jiancheng(wwwhost($_REQUEST['s_url']));
            $data=array();
            $data[$name]=$k;
            insertupdate("longzs.longzs_form_name",$data,"select id from longzs.longzs_form_name where $name='{$data[$name]}' or $name like '{$data[$name]}(%'","id",true);
            $rs=getrow("select $shoptype as name from longzs.longzs_form_name where $name = '{$k}'");
            if($rs['name']!="") {
                $replace_name=preg_replace("/\(.*$/","",$rs['name']);
                $max_tmp=0;
                if(preg_match("/\((.*)\)/",$rs['name'],$nn)){
                    $nn2=explode("|",$nn[1]);
                    foreach ($nn2 as $k2=>$v2){
                        $percent=customSimilarity($v2, $v);
                        if($percent>$max_tmp){
                            $max_tmp=$percent;
                            $v_tmp=$v2;
                        }
                    }
                }
                if($max_tmp===0){
                    $arr[$replace_name] = $v;
                }else{
                    $arr[$replace_name] = $v_tmp;
                }

            }else{
                $arr[$k] = $v;
            }
        }
    }

    if($name["goodsSn"]!="") {
        $arr["goodsSn"] = $pageinfo['prodata']['goodsSn'];
    }

    if($name["brand"]!="") {
        $arr["brand"] = $pageinfo['prodata']['brand'];
    }

    if($name["labs"]!="") {
        $arr["labs"] = "无限品牌";//$pageinfo['prodata']['labs']
    }

    if($name["labs"]!="") {
        $arr["labs"] = "无限品牌";//$pageinfo['prodata']['labs']
    }

    $sc->setData($arr);
    $result=$sc->getJs();
    echo $result;
    exit;
}
endjson($pageinfo);
exit;



